package xls;

import data.ExtramobiExcel;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: Vladimir
 * Date: 27.01.13 Time: 10:12
 */
public class LinkPriceParser {
    public static void main(String[] args) throws IOException {
        String pricePath = "G:\\projects\\my-im-tools\\data\\temp\\link\\link.xls";
        String picsPath = "G:\\projects\\my-im-tools\\images\\link\\";
        InputStream in = new FileInputStream(pricePath);
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.rowIterator();
        List<PriceData> priceDataList = new ArrayList<PriceData>();
        while(rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getCell(1).getCellType() != Cell.CELL_TYPE_NUMERIC) {
                continue;
            } else {
                PriceData priceData = new PriceData();
                priceData.name = ExtramobiExcel.getCellValue(row, 2);
                priceData.brand = ExtramobiExcel.getCellValue(row, 3);
                priceData.num = (int) row.getCell(1).getNumericCellValue();
                priceData.price = (int) row.getCell(6).getNumericCellValue();
                priceDataList.add(priceData);
            }
        }
        File[] picFiles = new File(picsPath).listFiles();
        for (PriceData priceData : priceDataList) {
            int count = 0;
            for (File picFile : picFiles) {
                String fileName = filterPicFileName(picFile);
                if (fileName.startsWith(priceData.num + "")) {
                    System.out.println(priceData + " : " + picFile.getName());
                    String newFileName = priceData.name + (count == 0 ? "" : count) + ".jpg";
                    picFile.renameTo(new File(picsPath + newFileName));
                    count++;
                }
            }
        }
    }

    private static String filterPicFileName(File picFile) {
        String fileName = picFile.getName();
        fileName = fileName.replace("_","");
        fileName = fileName.replace(".jpg","");
        return fileName;
    }
}

class PriceData {
    String name;
    String brand;
    int num;
    int price;

    @Override
    public String toString() {
        return "PriceData{" +
                "name='" + name + '\'' +
                ", brand='" + brand + '\'' +
                ", num=" + num +
                ", price=" + price +
                '}';
    }
}